import { NextResponse, type NextRequest } from 'next/server'; import { getCustomerUser } from '@/app/lib/lumen-auth'; import { commerceDb } from '@/app/lib/commerce-db'; import { isAdmin } from '@/app/lib/admin'; import { sendEmail } from '@/app/lib/email'; import { env } from '@/app/lib/env'; import { displayOrderId } from '@/app/lib/orders'; import { previewReadyHtml, studioOrderMessageHtml } from '@/app/lib/order-emails'; import { activeProofRevision, customerRevisions, orderMessageConfig, ORDER_MESSAGE_LIMIT, PROOF_PUBLISH_STATUSES, STUDIO_MESSAGE_STATUSES } from '@/app/lib/order-messages'; import { generateMagicLink } from '@/app/lib/magic-link'; import { PRODUCTS, sizeLabel, type Orientation } from '@/app/lib/pricing'; import { FRAMES } from '@/app/data/frames'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; export async function POST( req: NextRequest, ctx: { params: Promise<{ id: string }> }, ) { const { id } = await ctx.params; const user = await getCustomerUser(); if (!user || !isAdmin(user.email)) { return NextResponse.json({ error: 'forbidden' }, { status: 403 }); } let body: { generationId?: unknown; note?: unknown; startRevision?: unknown; sendRevision?: unknown; resumeProof?: unknown } | null; try { body = await req.json(); } catch { return NextResponse.json({ error: 'invalid json' }, { status: 400 }); } if (!body || (body.note !== undefined && typeof body.note !== 'string') || (body.generationId !== undefined && (typeof body.generationId !== 'string' || !body.generationId))) { return NextResponse.json({ error: 'Invalid proof or message.' }, { status: 400 }); } const generationId = body.generationId; const note = body.note?.trim() ?? ''; const startRevision = body.startRevision === true; const sendRevision = body.sendRevision === true; const resumeProof = body.resumeProof; if (resumeProof !== undefined && (typeof resumeProof !== 'object' || resumeProof === null || !('generationId' in resumeProof) || typeof resumeProof.generationId !== 'string' || !('feedbackAt' in resumeProof) || typeof resumeProof.feedbackAt !== 'string' || generationId || !note || startRevision || sendRevision)) { return NextResponse.json({ error: 'Choose the current proof and enter a reply.' }, { status: 400 }); } if (startRevision && (!generationId || note)) { return NextResponse.json({ error: 'Select the current proof to start a revision.' }, { status: 400 }); } if (!generationId && !note) return NextResponse.json({ error: 'Enter a message to send.' }, { status: 400 }); if (note.length > ORDER_MESSAGE_LIMIT) { return NextResponse.json({ error: `Messages must be ${ORDER_MESSAGE_LIMIT} characters or fewer.` }, { status: 400 }); } const admin = commerceDb(); const { data: orderState, error: readError } = await admin .from('orders') .select('status, config, revision_note, updated_at, current_generation_id') .eq('id', id) .single(); if (readError && readError.code !== 'PGRST116') { console.error('[proof publish] Could not load order', id, readError.code); return NextResponse.json({ error: 'Could not load the order.' }, { status: 500 }); } if (!orderState) { return NextResponse.json({ error: 'order not found' }, { status: 404 }); } if (startRevision) { if (orderState.status !== 'awaiting_approval' || orderState.current_generation_id !== generationId) { return NextResponse.json({ error: 'The active proof changed. Reload the order and try again.' }, { status: 409 }); } const { data: reopened, error } = await admin.from('orders') .update({ status: 'revision_requested' }) .eq('id', id) .eq('status', 'awaiting_approval') .eq('current_generation_id', generationId) .eq('updated_at', orderState.updated_at) .select('id').maybeSingle(); if (error) { console.error('[proof publish] Could not start revision', id, error.code); return NextResponse.json({ error: 'Could not start the revision.' }, { status: 500 }); } if (!reopened) return NextResponse.json({ error: 'The order changed. Reload the order and try again.' }, { status: 409 }); return NextResponse.json({ ok: true }); } if (!(generationId ? PROOF_PUBLISH_STATUSES : STUDIO_MESSAGE_STATUSES).includes(orderState.status)) { return NextResponse.json({ error: generationId ? 'The order is no longer open for a new proof.' : 'This order is closed to messages.', }, { status: 409 }); } if (generationId) { if (generationId === orderState.current_generation_id) { return NextResponse.json({ error: 'Select a new render to send as the replacement proof.' }, { status: 409 }); } const { data: gen } = await admin .from('generations') .select('id') .eq('id', generationId) .eq('order_id', id) .maybeSingle(); if (!gen) return NextResponse.json({ error: 'generation not found for this order' }, { status: 404 }); } const revision = activeProofRevision(orderState); if (resumeProof && (!revision || revision.baseGenerationId !== resumeProof.generationId || revision.feedback.at !== resumeProof.feedbackAt)) { return NextResponse.json({ error: 'The proof or feedback changed. Review the latest order and try again.' }, { status: 409 }); } if (sendRevision && (!generationId || (revision?.draftId !== generationId && revision?.printUpscale?.generationId !== generationId))) { return NextResponse.json({ error: 'The revision changed. Open the current draft and try again.' }, { status: 409 }); } const history = orderMessageConfig(orderState.config); const isRevisedProof = !!generationId && !!orderState.current_generation_id; const at = new Date().toISOString(); const config = { ...history, ...(generationId ? { proofPublishedAt: at, proofIsRevision: isRevisedProof, revisionDraft: null } : {}), ...(resumeProof ? { proofReviewResumedAt: at, revisionDraft: null } : {}), ...(generationId && revision ? { sentRevisions: [...history.sentRevisions, { generationId, baseGenerationId: revision.baseGenerationId, feedbackAt: revision.feedback.at, feedback: { note: revision.feedback.note, at: revision.feedback.at, generationId: revision.baseGenerationId }, ...(revision.printUpscale?.generationId === generationId ? { printUpscale: revision.printUpscale } : {}), }], } : {}), revisions: customerRevisions(orderState.config, orderState.revision_note, orderState.updated_at), studioMessages: note ? [...history.studioMessages, { id: crypto.randomUUID(), note, at, ...(generationId ? { generationId } : {}) }] : history.studioMessages, }; // Save the message and proof pointer together. updated_at protects the // conversation from concurrent writes that leave the order status unchanged. const { data: order, error: updErr } = await admin .from('orders') .update(generationId ? { current_generation_id: generationId, status: 'awaiting_approval', revision_note: null, config, } : resumeProof ? { status: 'awaiting_approval', revision_note: null, config } : { config }) .eq('id', id) .eq('status', orderState.status) .eq('updated_at', orderState.updated_at) .select('id, user_email, config') .maybeSingle(); if (updErr) { console.error('[proof publish] Could not save order update', id, updErr.code); return NextResponse.json({ error: 'Could not save the order update.' }, { status: 500 }); } if (!order) { return NextResponse.json({ error: 'The order changed while you were editing. Review its latest state and try again.' }, { status: 409 }); } if (generationId) { // Keep the historical flag in sync for older readers. The order's // current_generation_id controls which proof is active. const [prior, current] = await Promise.all([ admin.from('generations').update({ published: false }).eq('order_id', id).eq('published', true).neq('id', generationId), admin.from('generations').update({ published: true }).eq('order_id', id).eq('id', generationId), ]); if (prior.error || current.error) console.error('[proof publish] Could not sync generation flags', id); } // Resolve a human-readable description of the frame the customer // picked, so the email can name it ("Walnut Box Frame Matted Print, // 12 × 16 in") and set expectations for what they'll see on the // framed approve page. const cfg = (order.config ?? {}) as { productId?: 'matted' | 'canvas' | 'classic' | 'stretched'; size?: string; orientation?: Orientation; frame?: string; }; const product = cfg.productId ? PRODUCTS[cfg.productId] : null; // Transposed for landscape orders so the email names the real shape // ("10 × 8 in" not "8 × 10 in"). const sizeLabelStr = product && cfg.size ? sizeLabel(cfg.productId, cfg.size, cfg.orientation ?? 'portrait') : null; const frameLabel = cfg.frame ? FRAMES[cfg.frame as keyof typeof FRAMES]?.label : null; const frameDescription = product && sizeLabelStr ? `${frameLabel ? `${frameLabel} ` : ''}${product.label}, ${sizeLabelStr}` : null; const path = generationId || resumeProof || orderState.status === 'awaiting_approval' && !!orderState.current_generation_id ? `/orders/${order.id}/approve` : `/orders/${order.id}`; try { const link = await generateMagicLink(order.user_email, path) ?? `${env.site.url()}${path}`; const orderRef = displayOrderId(order.id); await sendEmail({ to: order.user_email, subject: generationId ? `Your ${isRevisedProof ? 'revised ' : ''}Lumen & Gesso proof is ready — ${orderRef}` : `A note from Lumen & Gesso — ${orderRef}`, html: generationId ? previewReadyHtml(order.id, link, frameDescription, note) : studioOrderMessageHtml(order.id, link, note, path.endsWith('/approve')), text: generationId ? `Your portrait proof is ready.${note ? `\n\nA note from the studio:\n${note}` : ''}\n\nReview it: ${link}` : `A note from the studio:\n${note}\n\nView your order: ${link}`, }); return NextResponse.json({ ok: true, emailSent: true }); } catch { console.error('[proof publish] Order update saved but email failed', id); return NextResponse.json({ ok: true, emailSent: false }); } }